package com.neusoft.tyut.hrs.service.impl;

import com.neusoft.tyut.hrs.comon.CommonResult;
import com.neusoft.tyut.hrs.comon.ResultCode;
import com.neusoft.tyut.hrs.comon.entity.Emp;
import com.neusoft.tyut.hrs.comon.util.JwtUtil;
import com.neusoft.tyut.hrs.mapper.EmpMapper;
import com.neusoft.tyut.hrs.mapper.EmploginfoMapper;
import com.neusoft.tyut.hrs.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
/** TODO : 将Mybatis执行结果转为为CommonResult */
public class EmpServiceImpl implements EmpService {
    @Autowired private EmpMapper empMapper;
    @Autowired private EmploginfoMapper emploginfoMapper;

    @Override
    public CommonResult findByEmpno(Integer empno, String logpwd) {
        Emp emp = new Emp();
        if (emp == null) {
            String msg = "此LOGID ： " + empno + "不存在";
            return CommonResult.fail(ResultCode.LOGID_IN_FREE);
        } else if (emp.getLogpwd().equals(logpwd)) {
            return CommonResult.success(emp);
        } else {
            return CommonResult.fail(ResultCode.LOGIN_PASSWORD_ERROR);
        }
    }

    @Override
    public CommonResult login(String logid, String logpwd) {
        Emp emp = emploginfoMapper.findByEmpno(Integer.parseInt(logid));
        if (Objects.isNull(emp)) {
            String msg = "此LOGID ： " + logid + "不存在";
            return CommonResult.fail(ResultCode.LOGID_IN_FREE);
        } else if (emp.getLogpwd().equals(logpwd)) {
            emp = empMapper.findByEmpno(emp.getEmpno());
            if (Objects.isNull(emp)) {
                String msg = "  应该通过Kafa向运维发提醒~~~~~~~~~~~ ";
                return CommonResult.fail(ResultCode.LOGID_IN_FREE);
            }
            try {
                String token = JwtUtil.createToken(emp);
                emp.setToken(token);
            } catch (Exception e) {
                return CommonResult.fail(500, e.getMessage());
            }

            return CommonResult.success(emp);
        } else {
            return CommonResult.fail(ResultCode.LOGIN_PASSWORD_ERROR);
        }
    }
}
